package com.bw.config.security;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.bw.common.JwtUtils;
import com.bw.entity.LoginUser;
import com.bw.exception.CustomerAuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class TokenValidFilter extends OncePerRequestFilter {


    @Autowired
    private LoginFailHandler loginFailHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            //校验token
            String token = request.getHeader("token");
            //如果没有token 则放行 交给后续的过滤器处理
            if (ObjectUtil.isEmpty(token)) {
                filterChain.doFilter(request, response);
                return;
            }
            boolean flag = JwtUtils.validToken(token);
            if (!flag) {
                throw new CustomerAuthenticationException("token已过期");
            }

            //如果存在token，则从token中解析出用户
            LoginUser userDetails = JSON.parseObject(JwtUtils.parseToken(token), LoginUser.class);


            //创建身份验证对象
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //设置到Spring Security上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //获取当前登录用户的方法
//            SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (AuthenticationException e) {
            loginFailHandler.onAuthenticationFailure(request, response, e);
        }
        filterChain.doFilter(request, response);
    }
}
